'use strict';

exports.main = async (event, context) => {
	const { username, password } = event;
	
	if (!username || !password) {
		return {
			code: -1,
			message: '用户名和密码不能为空'
		}
	}
	
	const db = uniCloud.database();
	const userCollection = db.collection('users');
	
	// 查询用户
	const userRes = await userCollection.where({
		username: username,
		password: password
	}).get();
	
	if (userRes.data.length === 0) {
		return {
			code: -1,
			message: '用户名或密码错误'
		}
	}
	
	const userInfo = userRes.data[0];
	
	// 生成token
	const token = Math.random().toString(36).substr(2);
	
	// 更新用户token
	await userCollection.doc(userInfo._id).update({
		token: token,
		updateTime: Date.now()
	});
	
	// 返回用户信息和token
	return {
		code: 0,
		message: '登录成功',
		data: {
			userInfo: {
				_id: userInfo._id,
				username: userInfo.username,
				nickname: userInfo.nickname,
				avatar: userInfo.avatar,
				signature: userInfo.signature,
				isVip: userInfo.isVip,
				isAdmin: userInfo.isAdmin
			},
			token: token
		}
	}
}; 